package com.jiangyg.devtools;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.popup.IPopupChooserBuilder;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.jiangyg.devtools.entity.ToolItem;
import com.jiangyg.devtools.execute.IToolExecutor;
import com.jiangyg.devtools.execute.beantojson.BeanToJsonToolExecutor;
import com.jiangyg.devtools.execute.camelcase.CamelCaseToolExecutor;
import com.jiangyg.devtools.execute.code.CodeGeneratorToolExecutor;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;

/**
 * 类描述：插件弹窗选项
 */
public class PluginAction extends AnAction {

    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        // 创建实例
        final JBPopupFactory instance = JBPopupFactory.getInstance();
        final IPopupChooserBuilder<ToolItem> builder = instance.createPopupChooserBuilder(tools());
        builder.setAutoselectOnMouseMove(true);
        // 设置标题
        builder.setTitle("开发工具");
        // 添加监听事件
        builder.setItemChosenCallback(tool -> exec(tool, event));
        // 创建弹窗并在屏幕中间显示
        final JBPopup popup = builder.createPopup();
        popup.showInFocusCenter();
    }

    private void exec(ToolItem tool, AnActionEvent event) {
        try {
            final Class<?> clazz = Class.forName(tool.getClazz());
            final Constructor<?> constructor = clazz.getConstructor(AnActionEvent.class);
            final IToolExecutor executor = (IToolExecutor) constructor.newInstance(event);
            executor.exec();
        } catch (Exception ex) {
            throw new DevtoolsException("启动插件报错", ex);
        }
    }

    private List<ToolItem> tools() {
        final List<ToolItem> tools = new ArrayList<>();
        tools.add(new ToolItem("code-generator", "代码生成器", CodeGeneratorToolExecutor.class.getName()));
        tools.add(new ToolItem("bean-to-json", "生成JSON", BeanToJsonToolExecutor.class.getName()));
        tools.add(new ToolItem("camel-case", "驼峰工具", CamelCaseToolExecutor.class.getName()));
//        tools.add(new ToolItem("test", "测试", TestToolExecutor.class.getName()));
        return tools;
    }

}
